package ahblue.cn.tanzi.ui.circle;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.kimkevin.cachepot.CachePot;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;

import java.util.Arrays;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.Result;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.jmessage.im.util.ToastUtil;
import ahblue.cn.tanzi.model.circle.CircleDynamicItem;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.ui.base.BaseActivity;
import ahblue.cn.tanzi.ui.home.article.AddCommentActivity;
import ahblue.cn.tanzi.util.DensityUtils;
import ahblue.cn.tanzi.util.GlideApp;
import ahblue.cn.tanzi.util.VipUtils;
import ahblue.cn.tanzi.view.ImageNineGridView;
import ahblue.cn.tanzi.view.ScaleTransitionPagerTitleView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 圈子中的动态详情
 */
public class DynamicDetailActivity extends BaseActivity {

    private static final int CODE_TO_START = 0x001;
    private static final int CODE_TO_END = 0x002;


    @BindView(R.id.textViewTitle)
    TextView mTextViewTitle;
    @BindView(R.id.imageButtonRight)
    ImageButton mImageButtonRight;

    @BindView(R.id.iv_circle_home_img)
    ImageView mImageViewHead;   // 头像
    @BindView(R.id.tv_circle_home_name)
    TextView mTextViewName;     // 姓名
    @BindView(R.id.tv_circle_home_time)
    TextView mTextViewTime;     // 发布时间
    @BindView(R.id.tv_circle_home_three_content)
    TextView mTextViewContent;  // 发布内容
    @BindView(R.id.tv_chakanquanbu)
    TextView tvShowMore;  // 展开 折叠
    @BindView(R.id.img_grid_layout)
    ImageNineGridView mImageNineGrid;   // 九宫格显示图片

    @BindView(R.id.iv_dynamicdetails_like)
    ImageView mImageViewLike;

    @BindView(R.id.tl_article_page_indicator)
    MagicIndicator mTabLayoutPage;
    @BindView(R.id.vp_article_viewpager)
    ViewPager mViewPagerArticle;

    @BindView(R.id.ll_model_circle_home_item_bottom)
    LinearLayout mLinearLayoutBottom;
    @BindView(R.id.sv_circle_shot_detail_content)
    ScrollView svCircleShotDetailContent;

    private LoginResultModel mLoginResultModel;

    private CircleDynamicItem mDynamicItem;

    //标识是否滑动到顶部
    private boolean isScrollToStart = false;
    //标识是否滑动到底部
    private boolean isScrollToEnd = false;

    private DynamicCommentFragment dynamicCommentFragment;
    private DynamicLikeFragment dynamicLikeFragment;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_TO_START:
                    //重置标志“滑动到顶部”时的标志位
                    isScrollToStart = false;
                    break;
                case CODE_TO_END:
                    //重置标志“滑动到底部”时的标志位
                    isScrollToEnd = false;
                    break;
                default:
                    break;
            }
        }
    };



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circle_shot_detail);
        ButterKnife.bind(this);
        mDynamicItem = CachePot.getInstance().pop(CircleDynamicItem.class);
        if (mDynamicItem == null) {
            ToastUtil.shortToast(this, "数据异常！");
            finish();
            return;
        }
        Log.e("kzg","***************************mDynamicItem:"+mDynamicItem.id);
        //addHeaderView();
        initData();
        initView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode==500){
            if (dynamicCommentFragment != null) {
                dynamicCommentFragment.initData();
            }
        }
    }

    private void initData() {
        mLoginResultModel = LoginResultModel.getUserModel(this, LoginResultModel.class);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        mViewPagerArticle.requestDisallowInterceptTouchEvent(false);
        svCircleShotDetailContent.requestDisallowInterceptTouchEvent(false);


        mLinearLayoutBottom.setVisibility(View.GONE);

        mTextViewTitle.setText("动态详情");

        updateDetail(mDynamicItem);

        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdapter(mNavigatorAdapter);
        mTabLayoutPage.setNavigator(commonNavigator);

        ArticleCategoryAdapter adapter = new ArticleCategoryAdapter(getSupportFragmentManager());
        mViewPagerArticle.setAdapter(adapter);
        ViewPagerHelper.bind(mTabLayoutPage, mViewPagerArticle);


        svCircleShotDetailContent.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                //滚动到顶部，ScrollView存在回弹效果效应（这里只会调用两次，如果用<=0,会多次触发）
                if (svCircleShotDetailContent.getScrollY() == 0) {
                    setFragmentCanScroll(false);
                    //过滤操作，优化为一次调用
                    if (!isScrollToStart) {
                        isScrollToStart = true;
                        mHandler.sendEmptyMessageDelayed(CODE_TO_START, 200);
                        Log.e("CustomScrollView", "toStart");
                    }
                } else {
                    View contentView = svCircleShotDetailContent.getChildAt(0);
                    if (contentView != null && contentView.getMeasuredHeight() == (svCircleShotDetailContent.getScrollY() + svCircleShotDetailContent.getHeight())) {
                        //滚动到底部，ScrollView存在回弹效果效应
                        setFragmentCanScroll(true);
                        //优化，只过滤第一次
                        if (!isScrollToEnd) {
                            isScrollToEnd = true;
                            mHandler.sendEmptyMessageDelayed(CODE_TO_END, 200);
                            Log.e("CustomScrollView", "toEnd");
                        }


                    }else {
                        setFragmentCanScroll(false);
                    }
                }
            }
        });



    }

    // 单击顶部“返回”
    @OnClick(R.id.imageButtonLeft)
    void onClickImageButtonLeft() {
        finish();
    }

    // 展开、收起
    @OnClick(R.id.tv_chakanquanbu)
    void onClickShowMoreButton() {
        if ("收起".equals(tvShowMore.getText().toString())) {
            mTextViewContent.setEllipsize(TextUtils.TruncateAt.END);//收起
            mTextViewContent.setLines(3);
            tvShowMore.setText("全文");
        } else {
            mTextViewContent.setEllipsize(null);//展开
            mTextViewContent.setSingleLine(false);//这个方法是必须设置的，否则无法展开
            tvShowMore.setText("收起");
        }
    }

    // 单击底部"点赞"
    @OnClick(R.id.iv_dynamicdetails_like)
    void onClickDynamicLike() {
        handleFabulous(mDynamicItem, mImageViewLike);
    }

    // 单击底部"写评论"
    @OnClick(R.id.tv_dynamicdetails_comment)
    void onClickComment() {
        //先判断是不是会员
        if (!VipUtils.checkVip(this)) {
            return;
        }
        final Intent intent = new Intent(this, AddCommentActivity.class);
        intent.putExtra(AddCommentActivity.ARG_ARTICAL_ID, mDynamicItem.id);
        intent.putExtra(AddCommentActivity.ARG_COMMENT_TYPE, 5);
        startActivityForResult(intent,500);

//        NiceDialog.init()
//                .setLayoutId(R.layout.dialog_dynamic_comment)
//                .setConvertListener(new ViewConvertListener() {
//                    @Override
//                    protected void convertView(ViewHolder viewHolder, BaseNiceDialog baseNiceDialog) {
//                        viewHolder.setOnClickListener(R.id.tv_send, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                EditText edComment = viewHolder.getView(R.id.edit_content);
//                                String comment = edComment.getText().toString();
//                                if (comment.length() == 0)
//                                    return;
//
//                                RemoteRepository repo = RemoteRepository.getsInstance();
//                                repo.addBigShotArticleComment(mDynamicItem.id, 5, comment,
//                                        mLoginResultModel.token, new ApiCallback<Result>() {
//                                            @Override
//                                            public void onSuccess(Result data) {
//                                                Toast.makeText(DynamicDetailActivity.this, "发布成功", Toast.LENGTH_LONG).show();
//                                                baseNiceDialog.dismiss();
//                                            }
//
//                                            @Override
//                                            public void onFailed(String errorMsg) {
//                                                Toast.makeText(DynamicDetailActivity.this, errorMsg, Toast.LENGTH_LONG).show();
//                                            }
//                                        });
//                            }
//                        });
//                    }
//                })
//                .setMargin(50)
//                .show(getSupportFragmentManager());
    }

    private void setFragmentCanScroll(boolean canScroll){
        if (dynamicCommentFragment != null){
            dynamicCommentFragment.setCanScrollable(canScroll);
        }
        if (dynamicLikeFragment != null){
            dynamicLikeFragment.setCanScrollable(canScroll);
        }
    }



    /**
     * 处理动态点赞和取消点赞的操作
     * @param data 需要处理的动态
     */
    private void handleFabulous(@NonNull CircleDynamicItem data, ImageView view) {
        RemoteRepository repo = RemoteRepository.getsInstance();
        if (data.is_fabulous == 0) {
            repo.addBigShotDynamicToFabulous(data.id, mLoginResultModel.token, new ApiCallback<Result>() {
                @Override
                public void onSuccess(Result result) {
                    data.is_fabulous = 1;
                    data.fabulous_count += 1;
                    setFabulousState(data, view);
                    if (dynamicLikeFragment != null) {
                        dynamicLikeFragment.initData();
                    }
                }

                @Override
                public void onFailed(String errorMsg) {

                }
            });
        } else {
            repo.deleteBigShotArticleDeleteDynamicFabulous(data.id, mLoginResultModel.token, new ApiCallback<Result>() {
                @Override
                public void onSuccess(Result result) {
                    data.is_fabulous = 0;
                    data.fabulous_count -= 1;
                    setFabulousState(data, view);
                    if (dynamicLikeFragment != null) {
                        dynamicLikeFragment.initData();
                    }
                }

                @Override
                public void onFailed(String errorMsg) {

                }
            });
        }
    }

    private void setFabulousState(CircleDynamicItem item, ImageView view) {
        int imgId = item.is_fabulous != 0 ? R.drawable.dynamic_icon_like_s : R.drawable.dynamic_icon_like_n;
        view.setImageResource(imgId);
    }

    private void updateDetail(CircleDynamicItem detail) {
        GlideApp.with(this).load(detail.member_avatar)
                .placeholder(R.drawable.user_default_avatar)
                .error(R.drawable.user_default_avatar)
                .into(mImageViewHead);

        mTextViewName.setText(detail.member_name);
        mTextViewContent.setText(detail.content);

        mTextViewContent.post(new Runnable() {
            @Override
            public void run() {
                if (mTextViewContent.getLineCount() > 3) {
                    mTextViewContent.setMaxLines(3);
                    tvShowMore.setVisibility(View.VISIBLE);
                } else {
                    tvShowMore.setVisibility(View.GONE);
                }
            }
        });

        if (detail.pic != null && detail.pic.length > 0) {
            List<String> imgUris = Arrays.asList(detail.pic);
            mImageNineGrid.render(imgUris);

            mImageNineGrid.setVisibility(View.VISIBLE);
        }

        setFabulousState(detail, mImageViewLike);
    }

    private String[] mTitles = new String[] { "评论", "点赞" };

    CommonNavigatorAdapter mNavigatorAdapter = new CommonNavigatorAdapter() {

        @Override
        public int getCount() {
            return mTitles.length;
        }

        @Override
        public IPagerTitleView getTitleView(Context context, int index) {
            ScaleTransitionPagerTitleView colorTransitionPagerTitleView = new ScaleTransitionPagerTitleView(context);
            colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.grey));
            colorTransitionPagerTitleView.setSelectedColor(getResources().getColor(R.color.blue_press));
            colorTransitionPagerTitleView.setTextSize(15);
            colorTransitionPagerTitleView.setText(mTitles[index]);
            colorTransitionPagerTitleView.setOnClickListener(view -> mViewPagerArticle.setCurrentItem(index));

            return colorTransitionPagerTitleView;
        }

        @Override
        public IPagerIndicator getIndicator(Context context) {
            LinePagerIndicator indicator = new LinePagerIndicator(context);
            indicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
            indicator.setLineHeight(DensityUtils.dp2px(context, 1.5f));
            indicator.setLineWidth(UIUtil.dip2px(context, 16));
            indicator.setYOffset(DensityUtils.dp2px(context, 3));
            indicator.setColors(getResources().getColor(R.color.blue_press));
            return indicator;
        }
    };

    /**
     * 文章分类ViewPager的adapter。
     */
    class ArticleCategoryAdapter extends FragmentPagerAdapter {

        ArticleCategoryAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            if (i == 0) {
                dynamicCommentFragment = DynamicCommentFragment.newInstance(mDynamicItem.id);
                return dynamicCommentFragment;
            } else if (i == 1) {
                dynamicLikeFragment = DynamicLikeFragment.newInstance(mDynamicItem.id);
                return dynamicLikeFragment;
            }

            return null;
        }

        @Override
        public int getCount() {
            return 2;
        }
    }


    public void setCommentCount(int count) {
        mTitles[0] = "评论（" + count + "）";
        mNavigatorAdapter.notifyDataSetChanged();
    }


    public void setLikeCount(int count) {
        mTitles[1] = "点赞（" + count + "）";
        mNavigatorAdapter.notifyDataSetChanged();
    }

}
